# 6. α混合（使用统一的显示和保存函数）
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt


def display_images(img1, img2, title1, title2):
    plt.figure(figsize=(10, 5))
    plt.subplot(1, 2, 1)
    plt.imshow(img1)
    plt.title(title1)
    plt.axis('off')

    plt.subplot(1, 2, 2)
    plt.imshow(img2)
    plt.title(title2)
    plt.axis('off')
    plt.tight_layout()
    plt.show()


def alpha_blend(foreground, background, alpha=0.5):
    # 输入检查
    if foreground.shape != background.shape:
        raise ValueError("前景和背景图像尺寸不匹配")

    # 转换到float类型
    fg = foreground.astype(float)
    bg = background.astype(float)

    # 执行混合
    blended = alpha * fg + (1.0 - alpha) * bg

    # 确保值在0-255范围内
    return np.clip(blended, 0, 255).astype(np.uint8)

if __name__ == "__main__":
    foreground = np.array(Image.open('face.png').convert('RGB'))
    height, width = foreground.shape[:2]
    background = np.ones((height, width, 3), dtype=np.uint8) * 255
    alpha = 0.7

    # 4. 执行混合
    blended = alpha_blend(foreground, background, alpha)

    # 5. 显示结果
    display_images(foreground, blended, "前景图像", f"混合结果(α={alpha})")